package org.jeecg.modules.rental.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.rental.vo.LoginRentalAccount;
import org.jeecg.modules.rental.entity.RentalAccountCoupon;
import org.jeecg.modules.rental.entity.RentalCouponCategory;
import org.jeecg.modules.rental.entity.RentalCouponWriteoff;
import org.jeecg.modules.rental.entity.RentalOrder;
import org.jeecg.modules.rental.mapper.RentalAccountCouponMapper;
import org.jeecg.modules.rental.mapper.RentalCouponCategoryMapper;
import org.jeecg.modules.rental.mapper.RentalCouponWriteoffMapper;
import org.jeecg.modules.rental.service.IRentalAccountCouponService;
import org.jeecg.modules.rental.vo.AccountCouponVO;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 账户卡券
 * @Author: sean
 * @Date:   2024-08-19
 * @Version: V1.0
 */
@Service
@RequiredArgsConstructor
public class RentalAccountCouponServiceImpl extends ServiceImpl<RentalAccountCouponMapper, RentalAccountCoupon> implements IRentalAccountCouponService {

    private final CacheManager cacheManager;

    private final RentalCouponWriteoffMapper couponWriteoffMapper;

    private final RentalCouponCategoryMapper rentalCouponCategoryMapper;

    @Override
    public IPage<RentalAccountCoupon> selectJoinPage(Page page, RentalAccountCoupon entity) {
        return baseMapper.selectJoinPage(page, entity);
    }

    @Override
    public List<AccountCouponVO> effectiveCoupons(BigDecimal price) {
        LoginRentalAccount rentalAccount = (LoginRentalAccount) SecurityUtils.getSubject().getPrincipal();
        List<RentalAccountCoupon> couponList = baseMapper.selectList(new QueryWrapper<RentalAccountCoupon>()
                .eq("account_id", rentalAccount.getId())
                .eq("status", "0")
                .le( ObjectUtil.isNotEmpty(price) && price.compareTo(BigDecimal.ZERO) > 0,"min_amount", price));
        List<AccountCouponVO> list = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(couponList)){
            List<RentalCouponCategory> couponCategories = rentalCouponCategoryMapper.selectList(new QueryWrapper<RentalCouponCategory>());
            Map<Long, List<RentalAccountCoupon>> listMap = couponList.stream()
                    .collect(Collectors.groupingBy(RentalAccountCoupon::getConfigId));
            listMap.forEach((key, value)->{
                //同类优惠券放在一起统计数量，显示离结束日期最近的一张
                RentalAccountCoupon rentalAccountCoupon = value.stream()
                        .min(Comparator.comparing(RentalAccountCoupon::getExpiryDate)).orElse(null);
                AccountCouponVO couponVO = new AccountCouponVO();
                BeanUtil.copyProperties(rentalAccountCoupon, couponVO);
                couponVO.setNum(value.size());
                RentalCouponCategory couponCategory = couponCategories.stream()
                        .filter(a-> a.getCode().equals(couponVO.getCouponCategory())).findFirst().orElse(null);
                if(ObjectUtil.isNotEmpty(couponCategory)){
                    couponVO.setCategoryName(couponCategory.getName());
                }
                list.add(couponVO);
            });

//            Map<String, Map<Long, List<RentalAccountCoupon>>> maps = couponList.stream()
//                    .collect(Collectors.groupingBy(RentalAccountCoupon::getSysOrgCode, Collectors.groupingBy(RentalAccountCoupon::getConfigId)));
//
//            Cache DeptCache = cacheManager.getCache(CacheConstant.SYS_DEPARTS_CACHE);
//            maps.forEach((k,v)->{
//                Map<Long, List<RentalAccountCoupon>> listMap = v;
//                Map map = new HashMap();
//                List<AccountCouponVO> list = new ArrayList<>();
//                listMap.forEach((key, value)->{
//                    //同类优惠券放在一起统计数量，显示离结束日期最近的一张
//                    RentalAccountCoupon rentalAccountCoupon = value.stream()
//                            .min(Comparator.comparing(RentalAccountCoupon::getExpiryDate)).orElse(null);
//                    AccountCouponVO couponVO = new AccountCouponVO();
//                    BeanUtil.copyProperties(rentalAccountCoupon, couponVO);
//                    couponVO.setNum(value.size());
//                    RentalCouponCategory couponCategory = couponCategories.stream()
//                            .filter(a-> a.getCode().equals(couponVO.getCouponCategory())).findFirst().orElse(null);
//                    if(ObjectUtil.isNotEmpty(couponCategory)){
//                        couponVO.setCategoryName(couponCategory.getName());
//                    }
//                    list.add(couponVO);
//                });
//                map.put("orgName",  k);
//                if(ObjectUtil.isNotEmpty(DeptCache)){
//                    //TODO 部门缓存
////                    SysDepartVO sysDepartVO = DeptCache.get(k, SysDepartVO.class);
////                    if(ObjectUtil.isNotEmpty(sysDepartVO)){
////                        map.put("orgName",  sysDepartVO.getDepartName());
////                    }
//                }
//                map.put("data", list);
//                result.add(map);
//            });
        }
        return list;
    }


    @Override
    @Transactional
    public Boolean handleCoupon(RentalOrder rentalOrder) {
        if (ObjectUtil.isEmpty(rentalOrder.getAccountCouponId())) {
            return false;
        }
        RentalAccountCoupon userCoupon = baseMapper.selectById(rentalOrder.getAccountCouponId());
        if (!"0".equals(userCoupon.getStatus())) {
            throw new JeecgBootException("该卡券你被使用");
        }
        userCoupon.setStatus("1");
        userCoupon.setUseTime(LocalDateTime.now());
        Boolean updateResult = baseMapper.updateById(userCoupon) > 0;

        RentalCouponWriteoff writeoff = new RentalCouponWriteoff();
        writeoff.setAccountCouponId(userCoupon.getId());
        writeoff.setOrderId(rentalOrder.getId());
        writeoff.setUseTime(LocalDateTime.now());
        writeoff.setDiscAmount(rentalOrder.getDiscountAmount());
        writeoff.setStoreId(rentalOrder.getMeshPointId());
        writeoff.setSysOrgCode(userCoupon.getSysOrgCode());
        Boolean insertResult = couponWriteoffMapper.insert(writeoff) > 0;
        return updateResult & insertResult;
    }
}
